package cuishifeng.blog.helper;


import org.apache.commons.io.IOUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Properties;

/**
 * @author cuishifeng
 * Created on 2021-01-31
 */
public class VelocityHelper {


    public static String getHtmlString(String template, Map<String, Object> paramMap) {
        VelocityEngine velocityEngine = new VelocityEngine();
        Properties props = new Properties();
        props.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
        props.put("runtime.log.logsystem.log4j.category", "velocity");
        props.put("runtime.log.logsystem.log4j.logger", "velocity");
        velocityEngine.init(props);
        VelocityContext vcl = new VelocityContext();
        paramMap.forEach((k, v) -> {
            vcl.put(k, v);
        });
        StringWriter sw = new StringWriter();
        velocityEngine.evaluate(vcl, sw, "cuishifeng-blog", template);
        return sw.toString();
    }

    public static String getHtmlString2(String templateFilePath, Map<String, Object> paramMap) throws IOException {
        URL url = VelocityHelper.class.getClassLoader().getResource(templateFilePath);
        assert url != null;
        String template = IOUtils.toString(url, Charset.forName("utf-8"));
        return getHtmlString(template, paramMap);
    }

}
